const {
  ERROR
} = require('../../common/error')
const {
  getNeedCaptcha,
  verifyCaptcha
} = require('../../lib/utils/captcha')
const {
  verifyEmailCode
} = require('../../lib/utils/verify-code')
const {
  userCollection,
  EMAIL_SCENE,
  CAPTCHA_SCENE,
  LOG_TYPE
} = require('../../common/constants')
const {
  findUser
} = require('../../lib/utils/account')
const PasswordUtils = require('../../lib/utils/password')

/**
 * 通过邮箱验证码更换邮箱
 * @param {object} params
 * @param {string} params.email   邮箱
 * @param {string} params.code   邮箱验证码
 * @param {string} params.captcha  图形验证码
 * @returns {object}
 */
module.exports = async function (params = {}) {
  const schema = {
    email: 'email',
    code: 'string',
    captcha: {
      required: true,
      type: 'string'
    }
  }
  this.middleware.validate(params, schema)
  const {
    email,
    code,
    captcha
  } = params

  const needCaptcha = await getNeedCaptcha.call(this, {
    email,
    type: LOG_TYPE.REPLACE_EMAIL
  })
  if (needCaptcha) {
    await verifyCaptcha.call(this, {
      captcha,
      scene: CAPTCHA_SCENE.REPLACE_EMAIL
    })
  }
  
  // 更新用户密码
  await userCollection.doc(uid).update({
    email
  })

  // 写入成功日志
  await this.middleware.uniIdLog({
    data: {
      email
    },
    type: LOG_TYPE.REPLACE_EMAIL
  })
  return {
    errCode: 0
  }
}
